package com.chinalife.project.util;

import org.jasypt.encryption.StringEncryptor;
import org.springframework.boot.CommandLineRunner;
import org.springframework.context.ApplicationContext;
import org.springframework.core.env.Environment;
import org.springframework.stereotype.Component;

@Component
public class EncryptUtil implements CommandLineRunner {

    private final ApplicationContext applicationContext;

    private final StringEncryptor encryptor;

    public EncryptUtil(ApplicationContext applicationContext, StringEncryptor encryptor) {
        this.applicationContext = applicationContext;
        this.encryptor = encryptor;
    }

    @Override
    public void run(String[] args) {

        Environment environment = applicationContext.getBean(Environment.class);

        // 首先获取配置文件里的原始明文信息 
        // 根据自己配置文件中的密码读取路径自行更改
        String userName    = environment.getProperty("spring.datasource.username");
        String oldPassword = environment.getProperty("spring.datasource.password");

        // 加密
        String encryptPassword = encrypt(oldPassword);
        String encryptUserName = encrypt(userName);

        // 打印加密前后的结果对比
        System.out.println("数据库原始明文用户为：" + userName);
        System.out.println("数据库原始明文用户加密后的结果为：" + encryptUserName);
        System.out.println("数据库原始明文密码为：" + oldPassword);
        System.out.println("数据库原始明文密码加密后的结果为：" + encryptPassword);
    }


    private String encrypt(String originPassord) {
        return encryptor.encrypt(originPassord);
    }

    private String decrypt(String encryptedPassword) {
        return encryptor.decrypt(encryptedPassword);
    }
}
